package com.meta.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.meta.api.param.UserNamePwdParam;
import com.meta.api.po.UserModel;
import com.meta.api.service.UserServiceQuery;
import com.meta.auth.vo.CorpUserInfoVO;

/**
 * @Author: xieZW
 * @Date: 2022/1/27 13:47
 */
@Component
public class MyCommonRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceQuery userServiceQuery;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        if (token instanceof UsernamePasswordToken) {
            UsernamePasswordToken principal = (UsernamePasswordToken) token;
            //query userInfo and set to shiro
            String username = principal.getUsername();
            char[] password = principal.getPassword();
            //query by  name and pwd
            UserNamePwdParam param = new UserNamePwdParam();
            param.setUsername(username);
            String s = String.valueOf(password);
            param.setPassword(s);
            UserModel login = userServiceQuery.login(param);
            CorpUserInfoVO corpUserInfoVO = new CorpUserInfoVO();
            corpUserInfoVO.setEmpPhone(login.getMobile());
            corpUserInfoVO.setEmpEmail(login.getEmail());
            corpUserInfoVO.setRealName(login.getUsername());
            corpUserInfoVO.setNickName(login.getUsername());
            corpUserInfoVO.setEmpName(login.getUsername());
            corpUserInfoVO.setUserId(login.getUserId());
            return new SimpleAuthenticationInfo(corpUserInfoVO, token.getCredentials(), this.getName());
        } else {
            return null;
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
